# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Renato Silva <br.renatosilva@gmail.com>

_realname=libjpeg-turbo
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=3.0.0
pkgrel=1
pkgdesc="JPEG image codec with accelerated baseline compression and decompression (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://libjpeg-turbo.virtualgl.org/"
license=(custom:'BSD-like')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             $( [[ "${CARCH}" == "aarch64" ]] || echo "${MINGW_PACKAGE_PREFIX}-nasm" ))
provides=("${MINGW_PACKAGE_PREFIX}-libjpeg")
conflicts=("${MINGW_PACKAGE_PREFIX}-libjpeg")
replaces=("${MINGW_PACKAGE_PREFIX}-libjpeg")
source=(${_realname}-${pkgver}.tar.gz::https://github.com/libjpeg-turbo/libjpeg-turbo/archive/${pkgver}.tar.gz
        "0001-header-compat.mingw.patch"
        "libjpeg-turbo-1.3.1-libmng-compatibility.patch")
sha256sums=('171dae5d73560bc94006a7c0c3281bd9bfde6a34f7e41e66f930a1a9162bd7df'
            '166264f617734b33ac55ec8b70e6636d4e409c0d837667afe158e9d28200e6dd'
            '16336caddc949a8a082f39c218b3289288d144bb3b87f62565ed1b294ff8e526')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -p1 -i ${srcdir}/0001-header-compat.mingw.patch
  patch -p1 -i ${srcdir}/libjpeg-turbo-1.3.1-libmng-compatibility.patch
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${_extra_config[@]} \
    -DWITH_JPEG8=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/ctest || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .

  cp "${srcdir}"/${_realname}-${pkgver}/{jinclude,transupp}.h ${pkgdir}${MINGW_PREFIX}/include/

  # Licenses
  # See https://www.libjpeg-turbo.org/About/License
  cd "${srcdir}/${_realname}-${pkgver}"
  install -Dm644 README.ijg            "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/README.ijg"
  install -Dm644 README.md  "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/README.md"
  install -Dm644 simd/nasm/jsimdext.inc "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/simd/jsimdext.inc"
}
